<template>
  <Page :title="navTitle" :on-page-back="onPageBack">
    <template #navBarCustom>
      <div class="nav-bar-btns flex">
        <div class="item flex items-center" @click="reload">
          <img class="icon mt-2px mr-8px" src="static/icons/refresh.png" mode="" />
          <span class="name text-white">刷新</span>
        </div>
      </div>
    </template>
    <template #content>
      <div class="w-full h-full p-20px box-border">
        <ScrollView
          ref="scroll"
          class="container w-full h-full bg-white overflow-scroll p-20px box-border"
        >
          <!-- 导学板块 -->
          <div class="sections">
            <div v-for="(section, index) in sections" :key="index" class="item mb-20px">
              <div class="submodule-item flex items-center font-medium">
                <div class="rect mr-6px"></div>
                <div class="title font-bold">
                  {{ (index + 1) | toChinesNum }}、{{ section.moduleTitle }}
                </div>
              </div>
              <div class="content">
                <div class="rich-text" v-html="section.moduleContent"></div>
                <div
                  class="submit text-white bg-51C3FF px-22px py-11px"
                  @click="submit(section)"
                  v-show="section.examId"
                >
                  {{ section.studentExamStatus ? '查看详情' : '去提交' }}
                </div>
                <div class="other-students" v-show="section.examId">
                  <div class="mb-14px">其他同学答卷</div>
                  <div class="student-list" v-if="section.guidanceStudentRespVOS.length">
                    <div
                      v-for="(student, studentIndex) in section.guidanceStudentRespVOS"
                      :key="studentIndex"
                      class="item flex flex-col items-center"
                      @click="goToStudentDetail(section, student)"
                    >
                      <div class="avatar text-white flex-center">
                        {{ student.studentName.slice(-2) }}
                      </div>
                      <div class="detail mt-6px">
                        <!-- 学生名字 -->
                        <span>{{ student.studentName }}</span>
                        <!-- 正确率 -->
                        <span class="text-30C9A1" v-if="student.studentAccuracy >= 0.8">
                          {{ Number(parseFloat(student.studentAccuracy * 100).toFixed(2)) }}%
                        </span>
                        <span class="text-F8AC23" v-else-if="student.studentAccuracy >= 0.4">
                          {{ Number(parseFloat(student.studentAccuracy * 100).toFixed(2)) }}%
                        </span>
                        <span class="text-FF4040" v-else>
                          {{ Number(parseFloat(student.studentAccuracy * 100).toFixed(2)) }}%
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="empty" v-else>无</div>
                </div>
              </div>
            </div>
          </div>
        </ScrollView>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page'
import ScrollView from '@/components/scroll-view'
import {
  getClassGuidanceItemApi,
  getClassGuidanceExamApi,
  getQuestionsApi
} from '@/api/class-guidance'
import { generateStudentAnswer } from '@/utils/question'
import { mapGetters } from 'vuex'

export default {
  filters: {
    toChinesNum(num) {
      if (!num) return ''
      let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
      let unit = ['', '十', '百', '千', '万']
      num = parseInt(num)
      let getWan = (temp) => {
        let strArr = temp.toString().split('').reverse()
        let newNum = ''
        let newArr = []
        strArr.forEach((item, index) => {
          newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index])
        })
        let numArr = []
        newArr.forEach((m, n) => {
          if (m !== '零') numArr.push(n)
        })
        if (newArr.length > 1) {
          newArr.forEach((m, n) => {
            if (newArr[newArr.length - 1] === '零') {
              if (n <= numArr[numArr.length - 1]) {
                newNum += m
              }
            } else {
              newNum += m
            }
          })
        } else {
          newNum = newArr[0]
        }

        return newNum
      }
      let overWan = Math.floor(num / 10000)
      let noWan = num % 10000
      if (noWan.toString().length < 4) {
        noWan = '0' + noWan
      }

      const result = overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)

      return result
    }
  },
  components: {
    Page,
    ScrollView
  },
  data() {
    return {
      loading: false,
      title: ' ', // 课堂导学标题
      subjectId: '', // 科目
      sections: [] // 导学板块
    }
  },
  computed: {
    ...mapGetters(['studentId']),
    navTitle() {
      try {
        const plainText = this.title
          .replace(/<[\w\W]*?>/gi, '') // 清空html标签
          .trim() // 清空首尾空格
          .replace('&nbsp;', '') // 清空空格标记

        return plainText
      } catch (error) {
        return ''
      }
    }
  },
  created() {
    this.init()
  },
  mounted() {
    this.$store.dispatch('initHomeworkStorage')
  },
  methods: {
    async init() {
      try {
        this.loading = true
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        })
        // 一分钟内加载不成功关闭loading弹窗
        const timer = setTimeout(() => {
          loading.close()
        }, 60000)

        const { id } = this.$route.query
        const { data } = await getClassGuidanceItemApi({ id })
        const { guidName, subject: subjectId, guidanceModuleRespVOS } = data

        this.title = guidName
        this.subjectId = subjectId
        this.sections = guidanceModuleRespVOS.map((item) => {
          const { guidanceStudentRespVOS } = item

          // 过滤学生
          item.guidanceStudentRespVOS = (guidanceStudentRespVOS || [])
            .map((student) => {
              if (student.studentId !== this.studentId && student.studentExamStatus !== 0) {
                return student
              } else {
                return null
              }
            })
            .filter((student) => student)

          return item
        })

        //关闭加载动画
        clearTimeout(timer)
        loading.close()
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    reload() {
      this.title = ' '
      this.subjectId = ''
      this.sections = []
      this.init()
    },
    async submit(section) {
      const { examId: id, studentExamStatus } = section
      const isSubmited = !!studentExamStatus

      if (!id) {
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内加载不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)
      // 获取作业详情
      const { data: record } = await getClassGuidanceExamApi({
        id
      })

      const { questionDataUrl, subject: subjectId } = record

      if (!questionDataUrl) {
        this.$message.error('获取题目失败')
        return
      }

      const res = await getQuestionsApi(questionDataUrl, { subjectId })

      //关闭加载动画
      clearTimeout(timer)
      loading.close()

      const questions = res.map((i, index) => {
        i['localStudentAnswer'] = {
          examId: id,
          questionId: i.questionId,
          studentId: this.studentId,
          completeFlag: index === res.length - 1 ? 1 : 0,
          studentAnswer: i.answerScoreable
            ? generateStudentAnswer({
                init: i.questionSplit.answer
              })
            : '',
          studentAnswerUrl: '',
          studentDuration: 0
        }
        // 答题状态 0 => 未答题 1 => 已答题
        i['localStudentAnswerStatus'] = 0
        i['extraInfo'] = {
          xkw: {}, // 学科网
          english: { stageIndex: 0 } // 英语听说
        }

        return i
      })

      this.$store.commit('setCurrentHomework', {
        record,
        questions,
        questionIndex: 0
      })

      if (!isSubmited) {
        // 查看是否存在缓存
        const { success, data } = await this.$storage.homework.getCacheItem(id)
        if (success) {
          try {
            const { questions: questionsCache } = data

            if (!(Array.isArray(questionsCache) && Array.isArray(questions))) return

            questionsCache.forEach((item) => {
              const { stem, answer, explanation, questionSplit, answerScoreable } = questions.find(
                (q) => item.questionId === q.questionId
              )

              // 重置stem
              item.stem = stem
              // 重置answer
              item.answer = answer
              // 重置explanation
              item.explanation = explanation
              // 重置questionSplit
              item.questionSplit = questionSplit
              // 重置answerScoreable
              item.answerScoreable = answerScoreable
            })
          } catch (error) {}

          this.$store.commit('setCurrentHomework', data)
        } else {
          this.$storage.homework.setCacheItem({
            id,
            value: {
              record,
              questions,
              questionIndex: 0
            }
          })
        }

        // 去提交
        if (subjectId == '66') {
          // 英语听说
          this.$router.push('/pages/homework/todo/question/english/index')
        } else {
          this.$router.push('/pages/homework/todo/question/xkw/index')
        }
      } else {
        // 查看详情
        if (subjectId == '66') {
          // 英语听说
          this.$router.push('/pages/homework/detail/question/english/index')
        } else {
          this.$router.push('/pages/homework/detail/question/xkw/index')
        }
      }
    },
    async goToStudentDetail(section, student) {
      const { examId: id } = section

      if (!id) {
        return
      }

      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      // 一分钟内加载不成功关闭loading弹窗
      const timer = setTimeout(() => {
        loading.close()
      }, 60000)
      // 获取作业详情
      const { data: record } = await getClassGuidanceExamApi({
        id
      })

      const { questionDataUrl, subject: subjectId } = record

      if (!questionDataUrl) {
        this.$message.error('获取题目失败')
        return
      }

      const res = await getQuestionsApi(questionDataUrl, { subjectId })

      //关闭加载动画
      clearTimeout(timer)
      loading.close()

      const questions = res.map((i, index) => {
        i['localStudentAnswer'] = {
          examId: id,
          questionId: i.questionId,
          studentId: this.studentId,
          completeFlag: index === res.length - 1 ? 1 : 0,
          studentAnswer: i.answerScoreable
            ? generateStudentAnswer({
                init: i.questionSplit.answer
              })
            : '',
          studentAnswerUrl: '',
          studentDuration: 0
        }
        // 答题状态 0 => 未答题 1 => 已答题
        i['localStudentAnswerStatus'] = 0
        i['extraInfo'] = {
          xkw: {}, // 学科网
          english: { stageIndex: 0 } // 英语听说
        }

        return i
      })

      this.$store.commit('setCurrentHomework', {
        record,
        questions,
        questionIndex: 0
      })

      if (subjectId == '66') {
        // 英语听说
        this.$router.push(
          `/pages/homework/detail/question/english/index?studentId=${student.studentId}`
        )
      } else {
        this.$router.push(
          `/pages/homework/detail/question/xkw/index?studentId=${student.studentId}`
        )
      }
    },
    onPageBack() {
      this.$router.back()
    }
  }
}
</script>

<style lang="scss" scoped>
.nav-bar-btns {
  .item {
    height: 30px;

    .icon {
      width: 22px;
      height: 22px;
    }

    .name {
      font-size: 22px;
      line-height: 22px;
    }
  }
}

.container {
  border-radius: 16px;

  .sections {
    .item {
      .submodule-item {
        font-size: 22px;

        .rect {
          width: 4px;
          height: 20px;
          background: linear-gradient(180deg, #51c3ff 0%, #31b3f7 100%);
          border-radius: 3px;
        }

        .title {
          font-family: 'sans-serif';
        }
      }

      .content {
        font-size: 20px;
        line-height: 28px;

        & > * {
          margin-top: 14px;
        }

        /deep/ table {
          border-collapse: collapse;
          border: 1px solid #ccc;

          td,
          th {
            border: 1px solid #ccc;
          }
        }

        .submit {
          display: inline-block;
          font-size: 18px;
          line-height: 18px;
          border-radius: 30px;
        }

        .other-students {
          .student-list {
            display: inline-grid;
            grid-template-columns: 130px 130px 130px 130px 130px 130px 130px 130px 130px;
            grid-column-gap: 3.5px;
            grid-row-gap: 10px;
            font-size: 16px;

            .item {
              width: 130px;

              .avatar {
                width: 60px;
                height: 60px;
                background: #f8ac23;
                color: #fff;
                border-radius: 60px 60px 60px 60px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
